// ignore_for_file: dangling_library_doc_comments, slash_for_doc_comments
/*** 
 * @Author: Zhong
 * @Date: 2025-03-21 13:59:18
 * @LastEditors: Zhong zhongxiaodong@eenet.com
 * @LastEditTime: 2025-07-16 16:17:59
 * @FilePath: /wan_android_flutter/lib/module_code/login/pages/login_page.dart
 * @Description: 
 */

import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:wan_android_flutter/common_code/extension/string_extension.dart';

import '../../../common_code/configs/app_color_config.dart';
import '../../../common_code/tabbar/bottom_nav_tabbar.dart';
import '../../../common_code/widgets/countdown_btn.dart';
import '../../../common_code/widgets/custom_checkbox.dart';
import '../api/api_login.dart';
import '../models/login_model.dart';
import 'register_page.dart';

class LoginPage extends StatefulWidget {
  static const String routeName = '/login';
  final Map arguments;
  const LoginPage({super.key, this.arguments = const {}});

  @override
  State<LoginPage> createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  //手机输入框controller
  final TextEditingController phoneTextEditController = TextEditingController(
    text: "15014212127",
  );
  //验证码输入框controller
  final TextEditingController msgCodeTextEditController = TextEditingController(
    text: "888888",
  );
  //checkbox状态
  bool _isChecked = false;

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: GestureDetector(
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            //顶部视图
            _buildTopView(),
            //主要内容视图
            _buildBodyView(),
          ],
        ),
        onTap: () {
          //点击空白区域收起键盘
          FocusScope.of(context).requestFocus(FocusNode());
        },
      ),
    );
  }

  //顶部视图
  Stack _buildTopView() {
    return Stack(
      children: [
        Container(
          width: double.infinity,
          height: 240.w,
          decoration: BoxDecoration(
            image: DecorationImage(
              image: AssetImage('assets/images/login_bg.png'),
              fit: BoxFit.cover,
            ),
          ),
        ),
        Positioned(
          left: 30.w,
          bottom: 80.w,
          child: Image.asset('assets/images/登录页文字内容.png'),
        ),
        Positioned(
          left: 0,
          right: 0,
          bottom: 0,
          child: Container(
            height: 20.w,
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.only(
                topLeft: Radius.circular(10),
                topRight: Radius.circular(10),
              ),
            ),
          ),
        ),
      ],
    );
  }

  //主要内容视图
  Expanded _buildBodyView() {
    return Expanded(
      flex: 1,
      child: Stack(
        alignment: Alignment.center,
        children: [
          Container(
            width: double.infinity,
            color: Colors.white,
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                //手机号输入框
                _buildPhoneView(),
                //验证码输入框
                _buildMsgCodeView(),
                //同意协议视图
                _buildCheckBoxView(),
                //登录按钮
                _buildLoginBtn(),
              ],
            ),
          ),
          //注册按钮
          Positioned(bottom: 20.w, child: _buildRegisterBtn()),
        ],
      ),
    );
  }

  //注册按钮
  TextButton _buildRegisterBtn() {
    return TextButton(
      onPressed: () {
        Get.toNamed(RegisterPage.routeName);
      },
      child: Text(
        "注册",
        style: TextStyle(
          color: AppColorConfig.themeColor,
          fontSize: 16.sp,
          fontWeight: FontWeight.bold,
        ),
      ),
    );
  }

  //手机号输入框
  Container _buildPhoneView() {
    return Container(
      color: Colors.white,
      height: 50,
      margin: EdgeInsets.only(left: 30.w, right: 30.w, top: 20.w),
      child: TextField(
        controller: phoneTextEditController,
        maxLength: 11,
        buildCounter:
            (
              context, {
              required currentLength,
              required isFocused,
              required maxLength,
            }) => null, //隐藏输入长度限制显示
        decoration: InputDecoration(
          //内容内边距，可设置光标起始位置，可让输入内容垂直居中
          contentPadding: const EdgeInsets.symmetric(vertical: 8.0),
          //框内左边内容
          prefixIcon: Padding(
            padding: const EdgeInsets.all(8.0),
            child: Container(
              width: 50,
              height: 40,
              color: Colors.white,
              alignment: Alignment.center,
              child: Text.rich(
                TextSpan(
                  children: [
                    TextSpan(
                      text: '+86',
                      style: TextStyle(
                        color: Color(0xff030915),
                        fontSize: 14.sp,
                      ),
                    ),
                    TextSpan(
                      text: ' |',
                      style: TextStyle(
                        color: Color(0xffE2E2E2),
                        fontSize: 18.sp,
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ),
          labelText: '请输入手机号',
          labelStyle: TextStyle(color: Color(0xff999999)),
          //不展示浮动文字
          floatingLabelBehavior: FloatingLabelBehavior.never,
          //默认边框
          enabledBorder: OutlineInputBorder(
            borderSide: BorderSide(color: Color(0xFFE2E2E2), width: 0.5),
            borderRadius: BorderRadius.all(Radius.circular(25)),
          ),
          //选中时的边框
          focusedBorder: OutlineInputBorder(
            borderSide: BorderSide(color: Color(0xFF0082FE), width: 0.5),
            borderRadius: BorderRadius.all(Radius.circular(25)),
          ),
        ),
        style: TextStyle(fontSize: 18.sp),
      ),
    );
  }

  //验证码输入框
  Container _buildMsgCodeView() {
    return Container(
      color: Colors.white,
      height: 50,
      margin: EdgeInsets.only(left: 30.w, right: 30.w, top: 20.w),
      child: TextField(
        controller: msgCodeTextEditController,
        maxLength: 6,
        buildCounter:
            (
              context, {
              required currentLength,
              required isFocused,
              required maxLength,
            }) => null, //隐藏输入长度限制显示
        decoration: InputDecoration(
          contentPadding: const EdgeInsets.symmetric(
            vertical: 8.0,
            horizontal: 20,
          ), //可设置光标起始位置，可让文本垂直居中
          suffixIcon: Padding(
            padding: const EdgeInsets.all(8.0),
            child: CountdownButton(
              normalText: '获取验证码',
              countdownText: '重试',
              normalTextStyle: TextStyle(
                fontSize: 15.sp,
                color: Colors.blue,
                fontWeight: FontWeight.w600,
              ),
              countdownTextStyle: TextStyle(
                fontSize: 15.sp,
                color: Colors.blueGrey,
                fontWeight: FontWeight.w600,
              ),
              countdownDuration: const Duration(seconds: 10),
              onPressed: () {
                // 在这里添加按钮点击后的逻辑
                debugPrint('按钮被点击了');
              },
            ),
          ),
          labelText: '请输入验证码',
          labelStyle: TextStyle(color: Color(0xff999999)),
          //不展示浮动文字
          floatingLabelBehavior: FloatingLabelBehavior.never,
          enabledBorder: OutlineInputBorder(
            borderSide: BorderSide(color: Color(0xFFE2E2E2), width: 0.5),
            borderRadius: BorderRadius.all(Radius.circular(25)),
          ),
          focusedBorder: OutlineInputBorder(
            borderSide: BorderSide(color: Color(0xFF0082FE), width: 0.5),
            borderRadius: BorderRadius.all(Radius.circular(25)),
          ),
        ),
        style: TextStyle(fontSize: 18.sp),
      ),
    );
  }

  //同意协议视图
  Padding _buildCheckBoxView() {
    return Padding(
      padding: const EdgeInsets.only(left: 30, top: 12),
      child: Row(
        children: [
          Padding(
            padding: const EdgeInsets.symmetric(horizontal: 8),
            child: CustomCheckbox(
              value: _isChecked,
              onChanged: (bool newValue) {
                setState(() {
                  _isChecked = newValue;
                });
              },
              activeColor: Colors.blue,
              borderWidth: 1.0,
              isRound: false,
              borderRadius: 10.0,
              size: 20.0,
            ),
          ),
          Text.rich(
            TextSpan(
              children: [
                TextSpan(
                  text: '我已阅读并同意',
                  style: TextStyle(color: Color(0xffAAABB7), fontSize: 12.sp),
                ),
                TextSpan(
                  text: '《服务协议》',
                  style: TextStyle(color: Colors.blue, fontSize: 12.sp),
                  recognizer: (() {
                    final recognizer = TapGestureRecognizer();
                    recognizer.onTap = () {
                      EasyLoading.showInfo('点击了服务协议');
                    };
                    return recognizer;
                  })(),
                ),
                TextSpan(
                  text: '及',
                  style: TextStyle(color: Color(0xffAAABB7), fontSize: 12.sp),
                ),
                TextSpan(
                  text: '《隐私协议》',
                  style: TextStyle(color: Colors.blue, fontSize: 12.sp),
                  recognizer: (() {
                    final recognizer = TapGestureRecognizer();
                    recognizer.onTap = () {
                      EasyLoading.showInfo('点击了隐私协议');
                    };
                    return recognizer;
                  })(),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  //登录按钮
  Container _buildLoginBtn() {
    return Container(
      margin: EdgeInsets.only(top: 50, left: 30, right: 30),
      width: double.infinity,
      height: 50.w,
      child: ElevatedButton(
        onPressed: () {
          //点击登录
          _requestLogin(
            mobile: phoneTextEditController.text,
            msgCode: msgCodeTextEditController.text,
          );
        },
        style: ElevatedButton.styleFrom(backgroundColor: Colors.blue),
        child: Text(
          '登录',
          style: TextStyle(
            fontSize: 16.sp,
            fontWeight: FontWeight.bold,
            color: Colors.white,
          ),
        ),
      ),
    );
  }

  //点击登录
  void _requestLogin({required String mobile, required String msgCode}) async {
    if (!mobile.isValidPhoneNumber) {
      EasyLoading.showToast('请输入正确手机号！');
      return;
    }

    if (msgCode.isEmpty) {
      EasyLoading.showToast('请输入验证码！');
      return;
    }

    if (!_isChecked) {
      EasyLoading.showToast('请勾选同意协议！');
      return;
    }

    LoginModelData.clearCacheData();
    bool isSuc = await ApiLogin.login(username: mobile, password: msgCode);
    if (isSuc) {
      Get.offAllNamed(BottomNavTabbar.routeName);
    }
  }
}
